package com.eqdd.yiqidian.ui.discover.workcircle

import android.Manifest
import android.content.Intent
import android.graphics.PorterDuff
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.view.View
import com.amap.api.maps2d.model.LatLng
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.http.HttpCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.kotlin.KotlinBaseActivity
import com.eqdd.yiqidian.map.SelectMapActivity
import com.eqdd.yiqidian.service.LocationObservable
import com.eqdd.yiqidian.ui.yiqiyue.ArticleInfoActivity
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.tbruyelle.rxpermissions.RxPermissions
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_work_circle_and_link.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast

/**
 * @author吕志豪 .
 * @date 18-3-31  上午10:01.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */
class WorkCircleLinkActivity : KotlinBaseActivity() {


    private var subscribe: Disposable? = null
    private var location: String = ""
    private var lat: Double = 39.908860
    private var lon: Double = 116.397390

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_work_circle_and_link)
        super.onCreate(savedInstanceState)
        iv_location.setColorFilter(0xffdfdfdf.toInt(), PorterDuff.Mode.SRC_IN)

        initTopBar("", "发送", View.OnClickListener {
            if (tv_message.text.isNullOrBlank()) {
                toast("请输入一些内容吧")
                return@OnClickListener
            }
            upload()
        })

        layout_link.onClick {
            val id = intent.getStringExtra("id").toInt()
            startActivity<ArticleInfoActivity>(Config.ID to id)
        }

        layout_location.onClick {
            startActivityForResult<SelectMapActivity>(Config.SELECT_MAP, Config.LAT to lat, Config.LON to lon)
        }

    }

    private fun initLocation() {
        RxPermissions.getInstance(this).request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe { isGrant ->
                    LocationObservable.setTime((5 * 60 * 1000).toLong())
                    subscribe = LocationObservable.get()
                            .subscribe { aMapLocation ->
                                if (aMapLocation.errorCode == 0) {
                                    lat = aMapLocation.latitude
                                    lon = aMapLocation.longitude
                                    location = aMapLocation.address
                                }
                            };
                }
    }

    override fun initData() {
        super.initData()
        val options = RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.insert_link)
                .error(R.drawable.insert_link)
        tv_link_text.text = intent.getStringExtra("title")
        initLocation()
        var imgUrl = intent.getStringExtra("image")
        if (imgUrl != null) {
            imgUrl = if (imgUrl.startsWith("http")) {
                imgUrl
            } else {
                HttpConfig.BASE_URL_NO + imgUrl
            }
            Glide.with(this)
                    .load(imgUrl)
                    .apply(options)
                    .into(iv_link_image)
        } else {
            Glide.with(this)
                    .load(R.drawable.insert_link)
                    .apply(options)
                    .into(iv_link_image)
        }


    }

    private fun upload() {
        val source = intent.getStringExtra("source")
        var type = 0
        if (source == "工作圈") {
            type = 1
        } else if (source == "易企阅") {
            type = 1
        } else if (source == "产品信息") {
            type = 1
        }
        /**

        //0:工作圈1:网页连接，2：视频，3：音乐，9：广告
        string type = context.Request.Form["type"];
        //转发来源的标题
        //转发来源
        //转发来源url
        //缩略图地址(相对路径)
        string imageUrl = context.Request.Form["imageUrl"];
         */
        val sourceTitle = intent.getStringExtra("title")
        val title = if (sourceTitle.length > 50) {
            sourceTitle.substring(0, 50)
        } else {
            sourceTitle
        }

        val imgUrl = intent.getStringExtra("image")
        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.FORWARD_WORK_CIRCLE)
                .params("companyId", user?.companyId ?: 0)
                .params("userGuid", user?.guid)
                .params("name", user?.uname)
                .params("type", type)
                .params("sourceTitle", title)
                .params("source", source)
                .params("sourceUrl", intent.getStringExtra("url"))
                .params("location", location)
                .params("message", tv_message.text.toString())
                .params("imageUrl", imgUrl.substring(HttpConfig.BASE_URL.length - 1, imgUrl.length))
                .execute(object : HttpCallBack<HttpResult<*>>(this@WorkCircleLinkActivity) {
                    override fun onSuccess(response: Response<HttpResult<*>>) {
                        val httpResult = response.body()
                        toast(httpResult.msg)
                        if (httpResult.status == 200) {
                            finish()
                        }
                    }

                    override fun onError(response: Response<HttpResult<*>>?) {
                        super.onError(response)
                    }
                })

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Config.SUCCESS && requestCode == Config.SELECT_MAP) {
            val color = ContextCompat.getColor(this, R.color.colorPrimary)
            location = data?.getStringExtra(Config.MAP_RESULT_STRING) ?: ""
            val latlon = data?.getParcelableExtra<LatLng>(Config.MAP_RESULT_LOCATION);
            lat = latlon?.latitude ?: lat
            lon = latlon?.longitude ?: lon
            tv_location.text = location
            iv_location.setColorFilter(color, PorterDuff.Mode.SRC_IN)
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        if (subscribe?.isDisposed != true) {
            subscribe?.dispose()
            subscribe = null
        }

    }

}